/**
 * 
 */
package it.unical.canonaco.rende.igpe.game.cbv.logiclayer.engine.events;

import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

/**
 * @author Massimo Canonaco
 *
 */
public class EventManager {
	private static EventManager instance;
	public static EventManager getInstance()
	{
		if(instance == null)
			instance = new EventManager();
		
		return instance;
	}
	
	/** */
	private HashMap<Float, LinkedList<EventListener>> listeners;
	
	private EventManager()
	{
		listeners = new HashMap<>();
	}
	public boolean addListener(final EventListener listener, final GenericEvent event)
	{
//		if(listeners == null)
//			listeners = new HashMap<>();
			
		final float EVENT = event.getGUID();
		LinkedList<EventListener> eventList = null;
		
		if(!listeners.containsKey(EVENT))
		{
			eventList = new LinkedList<>();
			eventList.add(listener);
			listeners.put(EVENT, eventList);
			return true;
		}
		else
		{
			return listeners.get(EVENT).add(listener);
		}
	}
	
	public boolean removeListener(final EventListener listener, final GenericEvent event)
	{
	 Iterator<EventListener>observers = listeners.get(event.getGUID()).iterator();
	while(observers.hasNext())
	{
		EventListener el = observers.next();
		if(el == listener)
			observers.remove();
	}
		
//		for (EventListener eventListener : observers) 
//		{
//			if(eventListener == listener)
//			{
//				
//			}
//		}
		return true;
	}
	
//	public boolean removeListener(final EventListener listener)
//	{
////		listeners.
////		for (iterable_type iterable_element : iterable) {
////			
////		}
//	}
	
	/** */
	public boolean triggerEvent(final GenericEvent event)
	{
		// Get observers for the event.
		LinkedList<EventListener> toSignal = listeners.get(event.getGUID());
		
		// If there're some observers for the event, signal them.
		if(toSignal != null)
		{
			for (EventListener eventListener : toSignal) 
			{
				eventListener.notify(event);
			}
		}
		
		return true;
	}
	
	public boolean queueEvent(final GenericEvent event)
	{
		return true;
	}
	
	public boolean abortEvent(final GenericEvent event)
	{
		return true;
	}
	
	public void update()
	{
		
	}
}
